import { GlobalHeaderContext } from '@/components/GlobalHeader/GlobalHeaderStore';
import { HeaderAPI } from '@/components/GlobalHeader/type';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getPosIDs, getTenantID, getUserID } from '@/utils';
import { message } from 'antd';
import { Ref, useContext, useEffect, useRef } from 'react';
import { resetLayoutService } from '../services';

export const ReloadLayoutModal: React.FC<HeaderAPI.IReloadLayoutModal> = ({ open, onClose }) => {
  /**
   * modal ref
   */
  const reloadLayoutRef: Ref<IOneModalRef> = useRef(null);

  const {
    baseLogin: { openWelcomeLayout },
    dispatch,
  } = useContext(GlobalHeaderContext);
  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (reloadLayoutRef) {
      if (reloadLayoutRef.current) {
        if (reloadLayoutRef.current.onModalCancel) {
          reloadLayoutRef.current.onModalCancel();
        }
      }
    }
  };

  useEffect(() => {
    return () => {
      if (openWelcomeLayout?.monitorLayout) {
        dispatch({
          type: 'baseLogin/changeWelocmeLayout',
          payload: {
            openWelcomeLayout: {
              ...openWelcomeLayout,
              monitorLayout: false,
              layoutLoading: false,
            },
          },
        });
      }
    };
  }, [openWelcomeLayout?.monitorLayout]);

  /**
   * 重置 布局回调
   * @param res
   */
  const reloadLayoutCall = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      dispatch({
        type: 'baseLogin/changeWelocmeLayout',
        payload: {
          openWelcomeLayout: {
            ...openWelcomeLayout,
            monitorLayout: true,
            layoutLoading: false,
          },
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入 重置布局接口
   */
  const { resetLayoutLoading, resetLayoutRun } = resetLayoutService(reloadLayoutCall);

  /**
   * 点击确认
   */
  const reloadOnOK = () => {
    let reloadParams: any = {
      layoutType: `${getTenantID()}10011001`,
      userID: getUserID(),
      userPositionID: getPosIDs(),
    };
    resetLayoutRun(reloadParams);
  };

  return (
    <>
      <OneModal
        open={open}
        ref={reloadLayoutRef}
        title={'重置布局'}
        width={document.body.clientWidth * 0.2}
        onCancel={onClose}
        bodyStyle={{
          padding: '15px 20px',
        }}
        centered
        confirmLoading={resetLayoutLoading}
        onOk={reloadOnOK}
      >
        <div
          style={{
            color: '#ff0000',
            fontSize: '18px',
          }}
        >
          重置后，首页布局将变成默认布局，无法恢复。是否确认重置？
        </div>
      </OneModal>
    </>
  );
};
